package org.sxdata.jingwei.util.CommonUtil;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.sxdata.jingwei.entity.UserEntity;
import org.sxdata.jingwei.service.UserService;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by admin on 2019/4/27.
 */
public class LoginFilter4CAS implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private String casCheckUrl;
    UserService userService;
    public void init(FilterConfig filterConfig) throws ServletException{
        casCheckUrl = filterConfig.getInitParameter("casCheckUrl");
    }

    /**
     * 与智能加载模块之间的认证流程如下：
     1. 点击“智能加载”模块 跳转到对应的url ,带上参数code ，code参数对应的值为一次性有效；
     2 . 智能加载模块 请求接口 http://ip:port/cafe.basic-service/openHTTP/checkCode?code=    带上code参数，接口支持get/post;
     3. 接口返回json形式如下：
     {"success":true,"message":null,"msgParams":null,"object":"admin","errorCode":null,"currentTime":1556368602321}
     success为true ，表示认证成功 ，且object对应的值为当前登录用户名，如果success 为false 则认证失败。
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
        if(StringUtils.isEmpty(casCheckUrl)){
            System.out.printf("casCheckUrl参数配置错误，请检查");
            return;
        }


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith("login.jsp")||requestURI.endsWith("/user/doLogin.do")){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        HttpSession session = request.getSession();
        UserEntity user= (UserEntity) session.getAttribute("login");
        if(user!=null){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String code = request.getParameter("code");

        //varify code
        String result = HttpUtil.httpGetRequest(casCheckUrl + code);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String success = jsonObject.getString("success");
        String loginUserName = jsonObject.getString("object");
        if("true".equals(success)){
            String username="admin", password="admin";
            try {
                if(userService==null){
                    userService= (UserService)SpringBeanHandler.getBean(UserService.class);
                }
                if("success".equals(userService.login(username,password,request))){
                    user= (UserEntity) session.getAttribute("login");
                    user.setLogin(loginUserName);
                    session.setAttribute("login", user);
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
                //check fail http://localhost:8080/login.jsp
                gotoLoginPage(response,request);
                return ;
            } catch (Exception e) {
                logger.error("自动登陆失败，请检查数据库中用户名密码是否正确。", e);
            }
        }


        gotoLoginPage(response,request);
        return ;

    }

    @Override
    public void destroy() {

    }

    private void gotoLoginPage(HttpServletResponse response,HttpServletRequest request ) throws IOException {

        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }
    public static void main(String[] args) {
        JSONObject jsonObject = JSONObject.fromObject("{\"success\":true,\"message\":null,\"msgParams\":null,\"object\":\"admin\",\"errorCode\":null,\"currentTime\":1556368602321}");
        String success = jsonObject.getString("success");

        String result = HttpUtil.httpGetRequest("http://47.101.146.75:8080/cafe.basic-service/openHTTP/checkCode?code=32cec81c-a9e5-4117-9b87-1430361947b4");
        System.out.printf(""+result);
    }

}
